package com.hod.client.client;

import com.google.gwt.gears.client.database.DatabaseException;
import com.google.gwt.user.client.Window;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.data.Record.Operation;
import com.gwtext.client.data.event.StoreListener;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.grid.BaseColumnConfig;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.EditorGridPanel;
import com.gwtext.client.widgets.grid.GridEditor;
import com.gwtext.client.widgets.grid.RowSelectionModel;
import com.gwtext.client.widgets.grid.event.RowSelectionListenerAdapter;
import com.gwtextux.client.data.PagingMemoryProxy;
import com.hod.client.backend.orm.client.GearsDataStore;
import com.hod.client.backend.orm.client.GearsQuery;
import com.hod.client.frontend.AbstractGrid;
import com.gwtext.client.core.EventObject;

public class ClientContactDataGrid extends EditorGridPanel {
	
	private GearsDataStore ds = null;
    private ColumnModel columnModel = getColumnConfigs();
    protected Store store;
    protected String idClient;
    
    
    protected static BaseColumnConfig[] columns = new BaseColumnConfig[]{
            new ColumnConfig("name", "name", 60, true, null, "name"),
            new ColumnConfig("address", "address", 60, true, null, "address"),
            new ColumnConfig("phone", "phone", 60, true, null, "phone"),
            new ColumnConfig("mobile", "mobile", 60, true, null, "mobile")
    };


    private static RecordDef recordDef = new RecordDef(
            new FieldDef[]{
                    new StringFieldDef("idClient"),
                    new StringFieldDef("idClientContactData"),
                    new StringFieldDef("name"),
                    new StringFieldDef("address"),
                    new StringFieldDef("phone"),
                    new StringFieldDef("mobile")
            }
    );

	

	public ClientContactDataGrid() {      
    }


    public ClientContactDataGrid(boolean small,final GearsDataStore ds,final String id) {
    	this.ds = ds;   
    	this.idClient = id;
    	getData(idClient);
      
        setColumnModel(columnModel);

        setFrame(true);
        setStripeRows(true);
        setIconCls("grid-icon");
        
        final RowSelectionModel sm = new RowSelectionModel(true);
        /*sm.addListener(new RowSelectionListenerAdapter() {
        	public void onRowSelect(RowSelectionModel sm, int rowIndex, Record record) {
        		
            }
        });*/
        setSelectionModel(sm);
        
        Toolbar toolbar = new Toolbar();
        for (BaseColumnConfig column:columns)
        	 ((ColumnConfig) column).setEditor(new GridEditor(new TextField()));

        ToolbarButton button = new ToolbarButton("Add Contact", new ButtonListenerAdapter() {
            public void onClick(Button button, EventObject e) {
            	ClientContactData rs = new ClientContactData();
            	rs.setIdClient(Integer.valueOf(idClient));
            	rs.setIdClientContactData(null);
                Record contactdata = recordDef.createRecord(new Object[]{rs.getIdClient(),rs.getIdClientContactData(),rs.getName(),rs.getAddress(),rs.getPhone(),rs.getMobile()});
                stopEditing();
                store.insert(0, contactdata);
                startEditing(0, 0);
            }
        });
        ToolbarButton button2 = new ToolbarButton("Save", new ButtonListenerAdapter() {
            public void onClick(Button button, EventObject e) {
            	try {
            		if (getSelectionModel()==null) Window.alert("Nulo");
	            	Record record = getSelectionModel().getSelected();
	            	ClientContactData cd = new ClientContactData();
	            	cd.setIdClient(record.getAsInteger("idClient"));
	            	cd.setIdClientContactData(record.getAsInteger("idClientContactData"));
	            	cd.setName(record.getAsString("name"));
	            	cd.setAddress(record.getAsString("address"));
	            	cd.setPhone(record.getAsString("phone"));
	            	cd.setMobile(record.getAsString("mobile"));            	            	
					ds.save(cd);					
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					Window.alert(e1.getMessage());
				}
				//Window.alert(cd.getName());
            }
        });
        
        toolbar.addButton(button);
        toolbar.addButton(button2);
        setClicksToEdit(1);
        setTopToolbar(toolbar);
        /*final PagingToolbar pagingToolbar = new PagingToolbar(store);
        pagingToolbar.setDisabled(false);
        pagingToolbar.setPageSize(5);
        pagingToolbar.setDisplayInfo(true);
        pagingToolbar.setDisplayMsg("Displaying clients {0} - {1} of {2}");
        pagingToolbar.setEmptyMsg("No records to display");
        NumberField pageSizeField = new NumberField();
        pageSizeField.setWidth(40);
        pageSizeField.setSelectOnFocus(true);
        pageSizeField.addListener(new FieldListenerAdapter() {
            public void onSpecialKey(Field field, EventObject e) {
                if (e.getKey() == EventObject.ENTER) {
                    int pageSize = Integer.parseInt(field.getValueAsString());
                    pagingToolbar.setPageSize(pageSize);
                }
            }
        });
        ToolTip toolTip = new ToolTip("Enter page size");
        toolTip.applyTo(pageSizeField);

        pagingToolbar.addField(pageSizeField);
        setBottomToolbar(pagingToolbar);*/
    }
    
    private void getData(String idClient){
    	PagingMemoryProxy proxy = null;
		try {
			GearsQuery q = this.ds.getNamedQuery(ClientContactData.FIND_ALL);
			q.setString(0, idClient);
			ClientContactData[] data = (ClientContactData[]) q.execute();
			ClientContactData rs = null;
			Object[][]data2 = new Object[data.length][];
			for (int i = 0; i < data.length; i++) {
                rs = data[i];	               
                data2[i] = new Object[]{rs.getIdClient(),rs.getIdClientContactData(),rs.getName(),rs.getAddress(),rs.getPhone(),rs.getMobile()};
            }
                        
			proxy = new PagingMemoryProxy(data2);
			
			
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
			Window.alert(e.getMessage());
		} 

        ArrayReader reader = new ArrayReader(recordDef);
        store = new Store(proxy, reader);
        store.load();       
        setStore(store);
    }
    
    
    public void refresh(){    	
        
    }

    protected ColumnModel getColumnConfigs() {
        ColumnModel columnModel = new ColumnModel(columns);
        return columnModel;
    }

	public void refresh(String id) {
		// TODO Auto-generated method stub
		this.idClient = id;
		getData(id); 
    	reconfigure(store, columnModel);
        this.getView().refresh(true);
		
	}

}
